var vShell={
	promptStr:"VShell>",
	subCtx:[
			{name:"shell",depends:["./js/src/shell.js"]},
			{name:"cmd",depends:["./js/src/cmd.js","./js/src/util.js"]},
			{name:"sql",depends:["./js/src/sql.js","./js/src/util.js"]},
			{name:"calc",depends:["./js/src/calc.js"]}
	],
	currCtx:null
};

//设置编辑区并定位光标
vShell.setEditAndFocus=function(initStr){
	$(".inputArea").html(initStr);
	$(".inputArea").focus();
	
	var sel = window.getSelection();
	var range = document.createRange();
	range.selectNodeContents($(".inputArea").get(0));
	range.collapse(false);
	sel.removeAllRanges();
	sel.addRange(range);
};

//输出消息
vShell.showInfo=function(info){
	$(".userOutput").append("<p>"+info+"</p>");
};

//获取输入
vShell.getInput=function(){
	return $.trim($(".inputArea").text());
};

//清理输出
vShell.clearOutput=function(){
	$(".userOutput").html("");
};

//进入模式
vShell.enterCtx=function(ctx){
	vShell.currCtx=ctx;
	if(typeof vShell.currCtx.initCtx=='function'){
		vShell.currCtx.initCtx();
	}
	vShell.setEditAndFocus(vShell.currCtx.promptStr);
};

//监听按键事件
vShell.keyDownHandle=function(event){
	if(!!vShell.currCtx){
		return vShell.currCtx.keyDownHandle(event);
	}else{
		if(event.keyCode==13){
			/*
			 * 回车回车键
			 */
							
			var command=vShell.getInput();
			vShell.showInfo(command);
			command=command.replace(vShell.promptStr,"");
			if("clear"==command){
				vShell.clearOutput();
				vShell.setEditAndFocus(vShell.promptStr);
			}else{
				var hasCtx=false;
				var subCtx=vShell.subCtx;
				for(var i=0;i<subCtx.length;i++){
					if(command==subCtx[i].name){
						hasCtx=true;
						if(typeof subCtx[i].isload=='undefined'&&!subCtx.isload){
							var depends=subCtx[i].depends;
							if(depends.length>0){
								JSLoader.load(depends.shift(),function(){
									var depend=depends.shift();
									if(typeof depend!='undefined'){
										JSLoader.load(depend,arguments.callee);
									}else{
										vShell.enterCtx(window[subCtx[i].name]);
									}
								});
							}
							subCtx[i].isload=true;
						}else{
							vShell.enterCtx(window[subCtx[i].name]);
						}
						break;
					}
				}
				if(!hasCtx){
					vShell.showInfo("命令无效！");
					vShell.setEditAndFocus(vShell.promptStr);
				}
			}
			return false;
		}else if(event.keyCode==8){
			/*
			 * 删除键
			 */
			if(vShell.getInput()==vShell.promptStr){
				return false;
			}
		}
	}
};